package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @Description:
 * @Author: yp
 */

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;


    /**
     * 登录验证码发送
     * @param telephone
     * @return
     */
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        try {
           //1. 获得用户输入的手机号码
           //2. 生成验证码(4或者6位)
            Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
            //3. 使用阿里云发送短信验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
           //4. 把验证码存到redis(存5分钟)
            System.out.println(telephone + "的验证码是:" + validateCode);
            jedisPool.getResource().setex(RedisMessageConstant.SENDTYPE_LOGIN+"_"+telephone,60*5,validateCode.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    /**
     * 预约的验证码
     * @return
     */
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {
        try {
            //1.生成验证码  18824567890---189001    18824561820---189002
            Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
            //2.使用阿里云服务发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
            //3. 把生成验证码存到redis里面(存5分钟)
            jedisPool.getResource().setex(RedisMessageConstant.SENDTYPE_ORDER+"_"+telephone ,60*5,validateCode.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }


}
